package com.yuanqi.Common.Interceptor;

import com.yuanqi.Common.config.ThreadLocalConfig;
import com.yuanqi.Properties.JwtProperties;
import com.yuanqi.Utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Component
public class UserInterceptor implements HandlerInterceptor {
   @Autowired
    ThreadLocalConfig threadLocalConfig;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader(jwtProperties.getHeaderkey());
//       String token = "eyJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MzAyNzgxODEsInVzZXJJZCI6NDAwfQ.UiK18tsHQQ_UtC0XpGLaiBDL2WMoLu2GYP_iyRJ64-8";
        try {
            Claims claims = JwtUtil.parser(token,jwtProperties.getKey());
            Long id = Long.parseLong(claims.get("userId").toString());
            HashMap map = new HashMap();
            map.put("userId",id);
            map.put("token",token);
            threadLocalConfig.set(map);
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocalConfig.remove();
}
}
